package com.wkbb.sports.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wkbb.common.constants.CommonConstant;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.RoleTypeJsonDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.basic.UserInfoDto;
import com.wkbb.common.dto.basic.UserUnionDto;
import com.wkbb.common.enums.LoginTypeEnum;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private BasicFeignService basicFeignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<UserDto> login(Long accountId, String unionId, String openId, Long visitorUserId, String mobile, Integer miniApp) {
        log.info("*******login ******accountId:{},unionId:{},openId:{},visitorUserId:{},mobile:{}",accountId,unionId,openId,visitorUserId,mobile);

        Long realAccountId = accountId;
        Boolean isVisitUser = true;

        //1.根据手机号获取真实的userId
        ResultDTO<UserInfoDto> realUserResultDTO = basicFeignService.getUserByMobile(mobile);
        if (null != realUserResultDTO && realUserResultDTO.isSuccess()) {
            UserInfoDto realUserInfoDto = realUserResultDTO.getData();
            if (null != realUserInfoDto) {
                Long realUserId = realUserInfoDto.getId();
                log.info("realUserId:{}",realUserId);

                //如果手机号查询到的用户也是游客
                ResultDTO<UserDto> userResult = basicFeignService.getUserInfoByMobile(null,mobile);
                if (null != userResult && userResult.isSuccess()) {
                    UserDto realUserDto = userResult.getData();
                    String roleTypeJsonStr = JSON.toJSONString(realUserDto.getRoleType());
                    List<RoleTypeJsonDto> roleTypeJsonDtoList = JSONObject.parseArray(roleTypeJsonStr, RoleTypeJsonDto.class);
                    for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsonDtoList) {
                        if (null == roleTypeJsonDto.getOrgId()) {
                            return new ResultDTO(ErrorCode.MOBILE_NOT_REGISTER);
                        }
                    }
                }

                //查询union表中是否已经绑定了真实userId
                ResultDTO<List<UserUnionDto>> userBindResultDto = basicFeignService.getUserUnionList(null, unionId, realUserId);
                if (null != userBindResultDto && userBindResultDto.isSuccess() && null != userBindResultDto.getData()) {
                    List<UserUnionDto> userBindList = userBindResultDto.getData();
                    if(!userBindList.isEmpty())
                    {
                        for(UserUnionDto userUnionDto : userBindList)
                        {
                            //如果是accountId=1
                            if(accountId.equals(userUnionDto.getAccountId())&&!accountId.equals(CommonConstant.VISIT_ACCOUNT_ID))
                            {
                                isVisitUser = false;
                                break;
                            }
                        }

                        if(!isVisitUser)
                        {
                            realAccountId = userBindList.get(0).getAccountId();
                        }
                    }
                    else
                    {
                        //查询union表中是否已经绑定了真实userId
                        ResultDTO<UserUnionDto> userBindResult = basicFeignService.getUnionInfo(accountId, null, visitorUserId);
                        if (null != userBindResult && userBindResult.isSuccess() && null != userBindResult.getData()) {
                            UserUnionDto userBindDto = userBindResult.getData();
                            if(unionId.equals(userBindDto.getUnionId())&&!accountId.equals(CommonConstant.VISIT_ACCOUNT_ID))
                            {
                                isVisitUser = false;
                            }
                        }
                    }
                }

                log.info("isVisitUser:{}",isVisitUser);

                //如果是游客，需要替换userId
                if(isVisitUser)
                {
                    //查询union表中是否已经绑定了游客userId
                    ResultDTO<UserUnionDto> userUnionResultDto = basicFeignService.getUnionInfo(null, unionId, visitorUserId);
                    if (null != userUnionResultDto && userUnionResultDto.isSuccess() && null != userUnionResultDto.getData()) {
                        UserUnionDto userUnionDto = userUnionResultDto.getData();
                        Long tempUserId = userUnionDto.getUserId();
                        log.info("*******login ****tempUserId:{}**",tempUserId);
                        //未绑定真实userId
                        if (tempUserId.longValue() != realUserId.longValue() && tempUserId.longValue() == visitorUserId.longValue()) {
                            ResultDTO<Boolean> resultDTO = basicFeignService.bindUser(accountId, visitorUserId, realUserId);
                            if (null != resultDTO && resultDTO.isSuccess()) {
                                Boolean isBind = resultDTO.getData();
                                log.info("*******login ****isBind:{}**",isBind);
                                if (!isBind) {
                                    return new ResultDTO(ErrorCode.SECURITY_ACCESS_TOKEN_GENERATE_FAILURE);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                return new ResultDTO(ErrorCode.MOBILE_NOT_REGISTER);
            }
        }

        //重新登录，更新缓存信息
        UserDto userDto = new UserDto();
        userDto.setAccountId(realAccountId);
        userDto.setUnionId(unionId);
        userDto.setOpenId(openId);
        log.info("*******login ******realAccountId:{},unionId:{},openId:{}",realAccountId,unionId,openId);

        ResultDTO<UserDto> realUserResult = basicFeignService.doUserByOpen(LoginTypeEnum.MINI.getValue(),true,true,miniApp,userDto);

        //删除虚拟绑定的关联union、open表数据
        if(realAccountId.equals(CommonConstant.VISIT_ACCOUNT_ID))
        {
            if(realUserResult.isSuccess() && null!=realUserResult.getData()) {
                UserDto realUserDto = realUserResult.getData();
                if(!visitorUserId.equals(realUserDto.getId())) {
                    basicFeignService.clearVisitorLogin(LoginTypeEnum.MINI.getValue(),realAccountId,visitorUserId,unionId);
                }
            }
        }

        return realUserResult;
    }
}
